<template>
  <div class="chat-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div class="user-info" @click="showProfileModal = true">
          <a-avatar :size="40" :src="authStore.user?.avatar">
            {{ authStore.user?.displayName?.[0] || authStore.user?.username?.[0] }}
          </a-avatar>
          <div class="user-details">
            <div class="username">{{ authStore.user?.displayName || authStore.user?.username }}</div>
            <div class="status" :class="{ online: connectionStatus }">
              {{ connectionStatus ? '已连接' : '未连接' }}
            </div>
          </div>
        </div>
        <div class="header-actions">
          <a-button type="text" shape="circle" @click="showUserSearchModal = true" title="添加好友">
            <UserAddOutlined />
          </a-button>
          <a-button type="text" shape="circle" @click="handleLogout" title="退出登录">
            <LogoutOutlined />
          </a-button>
        </div>
      </div>

      <div class="chat-list">
        <div class="chat-list-header">
          <a-input
            v-model:value="searchQuery"
            placeholder="搜索聊天..."
            size="small"
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </div>

        <div class="chat-rooms">
          <div
            v-for="room in filteredChatRooms"
            :key="room.id"
            class="chat-room-item"
            :class="{ active: chatStore.currentChatRoom?.id === room.id }"
            @click="selectChatRoom(room)"
          >
            <div class="chat-room-avatar-container">
              <a-badge
                :count="room.unreadCount && room.unreadCount > 0 ? room.unreadCount : 0"
                :number-style="{
                  backgroundColor: '#ff4d4f',
                  fontSize: '11px',
                  fontWeight: '600',
                  minWidth: '18px',
                  height: '18px',
                  lineHeight: '18px',
                  borderRadius: '9px',
                  boxShadow: '0 0 0 1px #fff'
                }"
                class="unread-badge"
              >
                <a-avatar :size="48">
                  {{ getChatRoomDisplayName(room)[0] }}
                </a-avatar>
              </a-badge>
            </div>
            <div class="chat-room-info">
              <div class="chat-room-name">{{ getChatRoomDisplayName(room) }}</div>
              <div class="last-message" v-if="room.lastMessage">
                {{ room.lastMessage.content }}
              </div>
              <div class="last-time" v-if="room.lastMessage">
                {{ formatTime(room.lastMessage.createdAt) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="main-chat">
      <div v-if="!chatStore.currentChatRoom" class="no-chat-selected">
        <div class="welcome-message">
          <h2>欢迎使用聊天应用</h2>
          <p>选择一个聊天室开始对话</p>
        </div>
      </div>

      <div v-else class="chat-area">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="chat-info">
            <a-avatar :size="40">
              {{ getChatRoomDisplayName(chatStore.currentChatRoom)[0] }}
            </a-avatar>
            <div class="chat-details">
              <div class="chat-name">{{ getChatRoomDisplayName(chatStore.currentChatRoom) }}</div>
              <div class="chat-members">
                {{ chatStore.currentChatRoom.members.length }} 成员
                <span v-if="!connectionStatus" class="connection-status offline">
                  · 连接断开
                </span>
                <span v-else class="connection-status online">
                  · 已连接
                </span>
              </div>
            </div>
          </div>
          <div class="chat-actions">
            <a-button
              v-if="!connectionStatus"
              type="primary"
              size="small"
              @click="handleReconnect"
              :loading="isReconnecting"
            >
              重连
            </a-button>
            <a-button type="text" size="small" @click="scrollToBottom()" title="滚动到底部">
              ↓
            </a-button>
            <a-button type="text" shape="circle" title="聊天信息">
              <InfoCircleOutlined />
            </a-button>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="messages-container" ref="messagesContainer">
          <!-- 加载更多消息指示器 -->
          <div v-if="isLoadingMoreMessages" class="loading-more-indicator">
            <a-spin size="small" />
            <span>加载更多消息...</span>
          </div>

          <div
            v-for="message in chatStore.currentChatMessages"
            :key="message.id"
            class="message-item"
            :class="{ 'own-message': message.senderId === authStore.user?.id }"
          >
            <!-- 头像 -->
            <a-avatar
              :size="32"
              :src="message.senderId === authStore.user?.id ? authStore.user?.avatar : message.sender?.avatar"
              class="message-avatar"
            >
              {{ message.senderId === authStore.user?.id
                  ? (authStore.user?.displayName?.[0] || authStore.user?.username?.[0])
                  : (message.sender?.displayName?.[0] || message.sender?.username?.[0]) }}
            </a-avatar>

            <div class="message-content">
              <!-- 发送者名称 -->
              <div class="message-header">
                <span class="sender-name">
                  {{ message.senderId === authStore.user?.id
                      ? (authStore.user?.displayName || authStore.user?.username)
                      : (message.sender?.displayName || message.sender?.username) }}
                </span>
              </div>

              <!-- 消息气泡 -->
              <div class="message-bubble">
                <div class="message-text">{{ message.content }}</div>
                <!-- 时间显示在消息内容下方 -->
                <div class="message-footer">
                  <span class="message-time">{{ formatTime(message.createdAt) }}</span>
                  <span v-if="message.isEdited" class="edited-indicator">(已编辑)</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 正在输入指示器 -->
          <div v-if="chatStore.currentTypingUsers.length > 0" class="typing-indicator">
            <a-avatar :size="24">...</a-avatar>
            <div class="typing-text">
              {{ getTypingText() }}
            </div>
          </div>

          <!-- 滚动到底部按钮 -->
          <div
            v-if="!isUserAtBottom && chatStore.currentChatMessages.length > 0"
            class="scroll-to-bottom-btn"
            @click="scrollToBottom()"
          >
            <a-button type="primary" shape="circle" size="small">
              ↓
            </a-button>
          </div>
        </div>

        <!-- 消息输入区域 -->
        <div class="message-input-area">
          <div class="input-container">
            <a-textarea
              v-model:value="messageInput"
              placeholder="输入消息..."
              :auto-size="{ minRows: 1, maxRows: 4 }"
              @keydown="handleKeyDown"
              @input="handleTyping"
              class="message-input"
            />
            <a-button
              type="primary"
              shape="circle"
              :disabled="!messageInput.trim()"
              @click="sendMessage"
              class="send-button"
            >
              <SendOutlined />
            </a-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户搜索模态框 -->
    <a-modal
      v-model:open="showUserSearchModal"
      title="添加好友"
      :footer="null"
      width="400px"
    >
      <div class="user-search-content">
        <a-input
          v-model:value="userSearchQuery"
          placeholder="搜索用户名或邮箱..."
          @input="handleUserSearch"
          class="search-input"
        >
          <template #prefix>
            <SearchOutlined />
          </template>
        </a-input>

        <div class="search-results" v-if="searchResults.length > 0">
          <div
            v-for="user in searchResults"
            :key="user.id"
            class="user-item"
            @click="handleUserSelected(user)"
          >
            <a-avatar :size="32" :src="user.avatar">
              {{ user.displayName?.[0] || user.username?.[0] }}
            </a-avatar>
            <div class="user-info">
              <div class="user-name">{{ user.displayName || user.username }}</div>
              <div class="user-email">{{ user.email }}</div>
            </div>
          </div>
        </div>

        <div v-else-if="userSearchQuery && !isSearching" class="no-results">
          未找到用户
        </div>

        <div v-if="isSearching" class="searching">
          <a-spin size="small" /> 搜索中...
        </div>
      </div>
    </a-modal>

    <!-- 个人信息模态框 -->
    <ProfileModal v-model:open="showProfileModal" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  UserAddOutlined,
  UserOutlined,
  LogoutOutlined,
  SearchOutlined,
  InfoCircleOutlined,
  SendOutlined
} from '@ant-design/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { useChatStore } from '@/stores/chat'
import { signalRService } from '@/services/signalr'
import type { ChatRoom, User, MessageType } from '@/types'
import ProfileModal from '@/components/ProfileModal.vue'
// import CreateChatModal from '@/components/CreateChatModal.vue'
// import UserSearchModal from '@/components/UserSearchModal.vue'

const router = useRouter()
const authStore = useAuthStore()
const chatStore = useChatStore()

const searchQuery = ref('')
const messageInput = ref('')
const showUserSearchModal = ref(false)
const showProfileModal = ref(false)
const userSearchQuery = ref('')
const searchResults = ref<User[]>([])
const isSearching = ref(false)
const messagesContainer = ref<HTMLElement>()
const typingTimer = ref<NodeJS.Timeout>()
const searchTimer = ref<NodeJS.Timeout>()
const connectionStatus = ref(false)
const isReconnecting = ref(false)
const isUserAtBottom = ref(true) // 用户是否在消息底部
const isLoadingMoreMessages = ref(false) // 是否正在加载更多消息

// 计算属性
const filteredChatRooms = computed(() => {
  if (!searchQuery.value) return chatStore.sortedChatRooms
  
  return chatStore.sortedChatRooms.filter(room =>
    getChatRoomDisplayName(room).toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 生命周期
onMounted(async () => {
  try {
    // 等待认证状态初始化完成
    await new Promise(resolve => {
      const checkAuth = () => {
        if (authStore.isAuthenticated || !localStorage.getItem('auth_token')) {
          resolve(true)
        } else {
          setTimeout(checkAuth, 100)
        }
      }
      checkAuth()
    })

    // 确保 SignalR 连接已建立
    if (!signalRService.isConnected && authStore.token) {
      try {
        await signalRService.connect(authStore.token)
      } catch (error) {
        console.error('SignalR 连接失败:', error)
        message.error('连接聊天服务失败')
        return
      }
    }

    // 初始化 SignalR 监听器
    chatStore.initializeSignalRListeners()

    // 获取聊天室列表
    await chatStore.fetchChatRooms()

    // 监听连接状态变化
    const updateConnectionStatus = () => {
      connectionStatus.value = signalRService.isConnected
    }

    // 立即更新连接状态
    updateConnectionStatus()

    // 设置连接状态监听
    signalRService.onConnectionStateChanged(updateConnectionStatus)

    // 定期检查连接状态（降低频率）
    const connectionCheckInterval = setInterval(() => {
      updateConnectionStatus()
    }, 5000)

    // 添加滚动事件监听器
    nextTick(() => {
      if (messagesContainer.value) {
        messagesContainer.value.addEventListener('scroll', checkIfUserAtBottom)
      }
    })

    // 在组件卸载时清除定时器和事件监听器
    const originalOnUnmounted = () => {
      clearInterval(connectionCheckInterval)
      if (typingTimer.value) {
        clearTimeout(typingTimer.value)
      }
      if (searchTimer.value) {
        clearTimeout(searchTimer.value)
      }
      if (messagesContainer.value) {
        messagesContainer.value.removeEventListener('scroll', checkIfUserAtBottom)
      }
    }

    onUnmounted(originalOnUnmounted)
  } catch (error) {
    message.error('初始化聊天失败')
  }
})

// 监听当前聊天室变化，自动滚动到底部
watch(() => chatStore.currentChatMessages, (newMessages, oldMessages) => {
  nextTick(() => {
    // 只有当用户在底部时才自动滚动
    if (isUserAtBottom.value) {
      scrollToBottom()
    }

    // 性能优化：如果消息太多，清理一些旧消息（保留最近的500条）
    if (newMessages && newMessages.length > 500) {
      // 这里可以实现消息清理逻辑
      console.log('消息数量过多，建议实现消息清理机制')
    }
  })
}, { deep: true })

// 监听聊天室切换，立即滚动到底部
watch(() => chatStore.currentChatRoom, () => {
  nextTick(() => {
    isUserAtBottom.value = true
    scrollToBottom(false) // 立即滚动，不使用动画
  })
})

// 方法
const getChatRoomDisplayName = (room: ChatRoom): string => {
  if (room.type === 1) { // Direct chat
    const otherUser = room.members.find(member => member.id !== authStore.user?.id)
    return otherUser?.displayName || otherUser?.username || '未知用户'
  }
  return room.name
}

const formatTime = (dateString: string): string => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 24小时内
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
  }
}

const selectChatRoom = async (room: ChatRoom) => {
  try {
    await chatStore.selectChatRoom(room)
  } catch (error) {
    message.error('选择聊天室失败')
  }
}

const sendMessage = async () => {
  if (!messageInput.value.trim() || !chatStore.currentChatRoom) return

  try {
    await chatStore.sendMessage({
      chatRoomId: chatStore.currentChatRoom.id,
      content: messageInput.value.trim(),
      type: 1 as MessageType // Text message
    })
    messageInput.value = ''
  } catch (error) {
    message.error('发送消息失败')
  }
}

const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

const handleTyping = () => {
  if (!chatStore.currentChatRoom) return

  // 发送正在输入状态
  chatStore.startTyping(chatStore.currentChatRoom.id)

  // 清除之前的定时器
  if (typingTimer.value) {
    clearTimeout(typingTimer.value)
  }

  // 3秒后停止输入状态
  typingTimer.value = setTimeout(() => {
    if (chatStore.currentChatRoom) {
      chatStore.stopTyping(chatStore.currentChatRoom.id)
    }
  }, 3000)
}

const getTypingText = (): string => {
  const typingUsers = chatStore.currentTypingUsers
  if (typingUsers.length === 1) {
    return '正在输入...'
  } else if (typingUsers.length > 1) {
    return `${typingUsers.length} 人正在输入...`
  }
  return ''
}

// 检查用户是否在消息底部
const checkIfUserAtBottom = () => {
  if (messagesContainer.value) {
    const container = messagesContainer.value
    const scrollTop = container.scrollTop
    const scrollHeight = container.scrollHeight
    const clientHeight = container.clientHeight

    // 允许一些误差（50px），认为用户在底部
    const threshold = 50
    isUserAtBottom.value = scrollTop + clientHeight >= scrollHeight - threshold

    // 检查是否滚动到顶部，加载更多消息
    if (scrollTop < 100 && !isLoadingMoreMessages.value && chatStore.currentChatRoom) {
      loadMoreMessages()
    }
  }
}

// 加载更多历史消息
const loadMoreMessages = async () => {
  if (isLoadingMoreMessages.value || !chatStore.currentChatRoom) return

  isLoadingMoreMessages.value = true
  try {
    // 这里可以调用聊天store的方法加载更多消息
    // 暂时先记录当前滚动位置，加载完成后恢复
    const container = messagesContainer.value
    const oldScrollHeight = container?.scrollHeight || 0

    // TODO: 实现加载更多消息的逻辑
    // await chatStore.loadMoreMessages(chatStore.currentChatRoom.id)

    // 恢复滚动位置
    nextTick(() => {
      if (container) {
        const newScrollHeight = container.scrollHeight
        container.scrollTop = newScrollHeight - oldScrollHeight
      }
    })
  } catch (error) {
    console.error('加载更多消息失败:', error)
  } finally {
    isLoadingMoreMessages.value = false
  }
}

// 滚动到底部
const scrollToBottom = (smooth = true) => {
  if (messagesContainer.value) {
    const container = messagesContainer.value
    const scrollHeight = container.scrollHeight
    const clientHeight = container.clientHeight

    console.log('滚动信息:', { scrollHeight, clientHeight, currentScrollTop: container.scrollTop })

    if (smooth) {
      // 平滑滚动到底部
      container.scrollTo({
        top: scrollHeight,
        behavior: 'smooth'
      })
    } else {
      // 立即滚动到底部
      container.scrollTop = scrollHeight
    }

    // 更新用户位置状态
    isUserAtBottom.value = true
  }
}

const handleLogout = async () => {
  try {
    await authStore.logout()
    router.push('/login')
  } catch (error) {
    message.error('退出登录失败')
  }
}



const handleUserSearch = () => {
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }

  searchTimer.value = setTimeout(async () => {
    if (!userSearchQuery.value.trim()) {
      searchResults.value = []
      return
    }

    isSearching.value = true
    try {
      const users = await authStore.searchUsers(userSearchQuery.value.trim())
      // 过滤掉当前用户
      searchResults.value = users.filter(user => user.id !== authStore.user?.id)
    } catch (error) {
      message.error('搜索用户失败')
      searchResults.value = []
    } finally {
      isSearching.value = false
    }
  }, 300)
}

const handleUserSelected = async (user: User) => {
  try {
    const chatRoom = await chatStore.createDirectChat(user.id)
    showUserSearchModal.value = false
    userSearchQuery.value = ''
    searchResults.value = []
    selectChatRoom(chatRoom)
  } catch (error) {
    message.error('创建聊天失败')
  }
}

const handleReconnect = async () => {
  if (!authStore.token) {
    message.error('认证信息丢失，请重新登录')
    return
  }

  isReconnecting.value = true
  try {
    await signalRService.connect(authStore.token)
    message.success('重连成功')

    // 重新初始化监听器
    chatStore.initializeSignalRListeners()

    // 如果有当前聊天室，重新加入
    if (chatStore.currentChatRoom) {
      await signalRService.joinChatRoom(chatStore.currentChatRoom.id)
    }
  } catch (error) {
    console.error('重连失败:', error)
    message.error('重连失败，请检查网络连接')
  } finally {
    isReconnecting.value = false
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
  overflow: hidden;
}

.sidebar {
  width: 280px;
  background: white;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  min-width: 280px;
}

.sidebar-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-actions {
  display: flex;
  gap: 4px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.user-details {
  flex: 1;
}

.username {
  font-weight: 500;
  color: #1f2937;
}

.status {
  font-size: 12px;
  color: #6b7280;
}

.status.online {
  color: #10b981;
}

.chat-list {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-list-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
}

.chat-rooms {
  flex: 1;
  overflow-y: auto;
}

.chat-room-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-room-item:hover {
  background: #f9fafb;
}

.chat-room-item.active {
  background: #e6f7ff;
}

.chat-room-avatar-container {
  position: relative;
  flex-shrink: 0;
}

.unread-badge {
  position: relative;
}

.unread-badge :deep(.ant-badge-count) {
  min-width: 18px;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  font-size: 11px;
  font-weight: 600;
  border-radius: 9px;
  box-shadow: 0 0 0 1px #fff;
  background-color: #ff4d4f !important;
  animation: badgePulse 2s infinite ease-in-out;
}

@keyframes badgePulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
}

.chat-room-info {
  flex: 1;
  min-width: 0;
}

.chat-room-name {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
}

.last-message {
  font-size: 14px;
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.last-time {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 2px;
}

.main-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.no-chat-selected {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.welcome-message {
  text-align: center;
  color: #6b7280;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  height: 100vh;
  overflow: hidden;
}

.chat-header {
  padding: 12px 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  flex-shrink: 0;
  height: 70px;
}

.chat-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-details {
  flex: 1;
}

.chat-name {
  font-weight: 500;
  color: #1f2937;
}

.chat-members {
  font-size: 14px;
  color: #6b7280;
}

.connection-status {
  font-size: 12px;
}

.connection-status.online {
  color: #10b981;
}

.connection-status.offline {
  color: #ef4444;
}

.chat-actions {
  display: flex;
  gap: 8px;
}

.messages-container {
  flex: 1;
  overflow-y: scroll;
  overflow-x: hidden;
  padding: 16px;
  background: #f5f5f5;
  scroll-behavior: smooth;
  position: relative;
  /* 确保在移动设备上也能正常滚动 */
  -webkit-overflow-scrolling: touch;
  /* 设置最小高度，确保有足够的滚动空间 */
  min-height: 200px;
  /* 优化滚动性能 */
  will-change: scroll-position;
}

.loading-more-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  color: #6b7280;
  font-size: 14px;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
  max-width: 100%;
  position: relative;
}

.message-item.own-message {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
  margin-top: 0;
  margin-right: 8px;
  width: 32px;
  height: 32px;
}

.own-message .message-avatar {
  margin-right: 0;
  margin-left: 8px;
}

.message-content {
  max-width: 400px;
  min-width: 0;
  position: relative;
}

.message-header {
  margin-bottom: 4px;
}

.sender-name {
  font-weight: 500;
  color: #666;
  font-size: 12px;
}

/* 自己的消息名称右对齐 */
.own-message .message-header {
  text-align: right;
}

.message-bubble {
  background: #ffffff;
  border-radius: 8px;
  padding: 10px 12px;
  position: relative;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  word-wrap: break-word;
  border: 1px solid #e0e0e0;
  display: inline-block;
}

.own-message .message-bubble {
  background: #007aff;
  color: white;
  border: 1px solid #007aff;
}

/* 移除消息气泡尾巴效果，保持简洁 */

.message-text {
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-wrap;
  line-height: 1.4;
  max-width: 100%;
  overflow-wrap: break-word;
  font-size: 14px;
  margin: 0 0 6px 0;
}

.message-footer {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 4px;
  justify-content: flex-start; /* 默认左对齐（左边消息的时间在左下角） */
}

.message-time {
  font-size: 11px;
  color: #999;
}

.own-message .message-time {
  color: rgba(255, 255, 255, 0.8);
}

/* 右边消息的时间在右下角 */
.own-message .message-footer {
  justify-content: flex-end;
}

.edited-indicator {
  font-style: italic;
  opacity: 0.7;
  font-size: 10px;
}

.own-message .edited-indicator {
  color: rgba(255, 255, 255, 0.8);
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #999;
  font-style: italic;
  padding: 8px 12px;
  margin: 4px 0;
  font-size: 13px;
}

.scroll-to-bottom-btn {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 10;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-input-area {
  padding: 12px 16px;
  border-top: 1px solid #e0e0e0;
  background: #ffffff;
  flex-shrink: 0; /* 确保输入区域不会被压缩 */
  position: relative;
  z-index: 5; /* 确保在滚动按钮之上 */
  min-height: 60px;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  width: 100%;
  max-width: 100%;
  background: #f8f8f8;
  border-radius: 20px;
  padding: 6px 12px;
  border: 1px solid #e0e0e0;
}

.input-container:focus-within {
  border-color: #007aff;
}

.message-input {
  flex: 1;
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
  resize: none;
  font-size: 14px;
}

.message-input:focus {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
}

.send-button {
  border-radius: 50% !important;
  width: 32px !important;
  height: 32px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  background: #007aff !important;
  border: none !important;
  color: white !important;
}

.send-button:disabled {
  background: #ccc !important;
  color: #999 !important;
}

/* 自定义滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 4px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .messages-container {
    padding: 12px;
  }

  .message-item {
    margin-bottom: 10px;
  }

  .message-content {
    max-width: 300px;
  }

  .message-bubble {
    padding: 8px 12px;
    border-radius: 8px;
  }

  .message-input-area {
    padding: 10px 12px;
  }

  .input-container {
    gap: 10px;
    padding: 5px 10px;
    border-radius: 18px;
  }

  .send-button {
    width: 28px !important;
    height: 28px !important;
  }
}

@media (max-width: 480px) {
  .message-content {
    max-width: 250px;
  }

  .message-bubble {
    padding: 8px 10px;
    font-size: 13px;
  }

  .message-avatar {
    width: 28px !important;
    height: 28px !important;
  }

  .message-text {
    font-size: 13px;
  }
}

.send-button {
  flex-shrink: 0;
  min-width: 40px;
  min-height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 用户搜索模态框样式 */
.user-search-content {
  padding: 8px 0;
}

.search-input {
  margin-bottom: 16px;
}

.search-results {
  max-height: 300px;
  overflow-y: auto;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-item:hover {
  background: #f5f5f5;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 2px;
}

.user-email {
  font-size: 12px;
  color: #6b7280;
}

.no-results, .searching {
  text-align: center;
  color: #6b7280;
  padding: 20px;
}

.searching {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
</style>
